﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using Warehouse.Web.AppCode;
using System.Data;
using System.Data.SqlClient;

namespace Warehouse.Web.Inventory
{
    public partial class Statistics : BasePage
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            DateTime startDate = DateTime.Now.Date.AddDays(1 - DateTime.Now.Day);
            DateTime endDate = DateTime.Now.Date;

            if (!IsPostBack)
            {
                if (Request.QueryString.AllKeys.Contains("search"))
                {
                    startDate = DateTime.Parse(Request.QueryString["start"]);
                    endDate = DateTime.Parse(Request.QueryString["end"]);
                }

                this.tbStartDate.Text = startDate.ToString("yyyy-MM-dd");
                this.tbEndDate.Text = endDate.ToString("yyyy-MM-dd");

                LoadData(startDate, endDate.AddDays(1));
            }
        }

        void LoadData(DateTime startDate, DateTime endDate)
        {

            string cmdText = "with tp as ( ";
            cmdText += "SELECT CONVERT(CHAR(7), [PurchaseDate], 120) as [Month],[HouseID],(case [Type] when 3 then -1 when 2 then 0 else 1 end)as [OP],[Amount] as [PurchaseAmount],0 as [SalesAmount] FROM [dbo].[PurchaseView] where [Status]=0 and [PurchaseDate]>=@StartDate and [PurchaseDate]<@EndDate ";
            cmdText += " union all ";
            cmdText += "select CONVERT(CHAR(7), [SalesDate], 120) as [Month],[HouseID],(case [Type] when 3 then -1 when 2 then 0 else 1 end)as [OP],0 as [PurchaseAmount],[Amount] as [SalesAmount] from [dbo].[SalesView] where [Status]=0 and [SalesDate]>=@StartDate and [SalesDate]<@EndDate";
            cmdText += ")select [Name],[Month],sum([PurchaseAmount]* [OP]) as [PurchaseAmount],sum([SalesAmount]* [OP]) as [SalesAmount] from tp join [Warehouse] on tp.[HouseID]= [WareHouse].ID group by [Month],[Name] order by [Name],[Month] asc";


            DataTable dt = DataAccess.WarehouseClassesDataContext.GetDataTable(cmdText, new List<SqlParameter>()
            {
                new SqlParameter("StartDate",startDate),
                new SqlParameter("EndDate",endDate)
            });

            this.rptData.DataSource = dt;
            this.rptData.DataBind();
        }
    }
}
